// import login from './Login'
// import { envInfo } from '@/config/index'
import { useStore } from '@/store/index'
// import UserInfoModule from '@/utils/loginUserInfo'
// 发布者
import Subject from '@/api/Subject'
// 订阅者
import Observer from '@/api/Observer'
import { login, wxlogin } from './member'

const subject = new Subject()
let __API_LOGIN_ = false
const store = useStore()

const request = (url: string, obj?: {
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS' | 'HEAD' | 'TRACE' | 'CONNECT',
  data?: string | ArrayBuffer | Record<string, any>
}) => {
  console.log('进来了 request', url)
  return new Promise((resolve, reject) => {
    // 判断是否登录接口，登录接口不需要toekn
    const arr: string[] = ['/member/wxMember/login']
    let token: string = store.token
    if (arr.includes(url)) {
      token = ''
    }
    uni.request({
      header: {
        // channel: envInfo.saleChannel,
        token
      },
      url: 'http://task-api.sooge.top' + url,
      method: obj?.method || 'GET',
      data: obj?.data,
      success: async (res) => {
        console.log('res --- res', res)
        // 这里可以判断 store 里是否有token，如果没有就去调用接口获取touken
        // if (!store.state.token) {
        // 静态登录 通过拿 code 登录 获取用户openid
        // 有openid有token  再设置到 store里去
        // let loginInfo = await login()
        // }
        if (res.statusCode === 401) {
          console.log('------request 401------', res)
          __API_LOGIN_ = false
          uni.showToast({
            title: '身份信息过期正在重新登陆',
            icon: 'loading'
          })
          store.setToken('')
          // 实例化订阅者
          const obs = new Observer(() => {
            request(url, obj)
              .then(res => {
                // 移除订阅者
                subject.remove(obs)
                resolve(res)
              }).catch(err => {
                reject(err)
              })
          })
          // 添加订阅者
          subject.add(obs)
          if (!__API_LOGIN_) {
            __API_LOGIN_ = true
            // 静默登录
            // const loginUserInfo = new UserInfoModule()
            const res = await silentWxLogin()
            // 登录完成
            if (res) {
              // 发布者 通知 订阅者
              subject.notify()
            }
          }
        }
        // 如果是登录接口就给缓存设置token
        if (url.includes('login')) {
          store.setToken(token)
        }
        // 结果返回
        if (res.statusCode === 200) {
          resolve(res.data)
        } else if (res.statusCode === 500) {
          console.log('request statusCode 500')
          reject(res.data)
        }
      },
      fail (err) {
        console.log('request fail', err)
        reject(err)
      }
    })
  })
}

// 代理拦截器，有token才正常放行，不然先调用静默登录再放行
const requestProxy = new Proxy(request, {
  get (target, key, receiver) {
    if (['request', 'get', 'delete', 'head', 'post', 'put', 'patch'].includes(key as string)) {
      return new Proxy(Reflect.get(target, key, receiver), {
        apply: this.apply
      })
    } else {
      return Reflect.get(target, key, receiver)
    }
  },
  apply (target, thisArg, args) {
    return new Promise(async (resolve, reject) => {
      const falg = !store.token && args[0] !== '/member/wxMember/login'
      if (falg) {
        // 实例化订阅者
        const obs = new Observer(() => {
          target(args[0], args[1] || {})
            .then(res => {
              // 移除订阅者
              subject.remove(obs)
              resolve(res)
            })
            .catch(err => {
              reject(err)
            })
        })
        // 添加订阅者
        subject.add(obs)
        // 登录判断
        if (!__API_LOGIN_) {
          __API_LOGIN_ = true
          // 静默登录
          const res = await silentWxLogin()
          // 登录完成
          if (res) {
            // 发布者 通知 订阅者
            subject.notify()
          }
        }
      } else {
        if (args[0] === '/member/wxMember/login') {
          __API_LOGIN_ = true
        }
        target(args[0], args[1] || {})
          .then(res => {
            resolve(res)
          })
          .catch(err => {
            reject(err)
          })
      }
    })
  }
})

// 登录
const silentLogin = async () => {
  const promise = new Promise(async (resolve, reject) => {
    const res = await login({
      mobile: '13332558952',
      code: '8888'
    })
    const { errcode = '', errmsg = '', result } = res || {}
    if (!errcode) {
      const { token = '' } = result || {}
      store.setToken(token)
      resolve(res)
    } else {
      reject(errmsg)
    }
  })
  return promise
}

// 微信登录
const silentWxLogin = async () => {
  const promise = new Promise(async (resolve, reject) => {
    uni.login({
      provider: 'weixin', // 使用微信登录
      success: async (loginRes) => {
        console.log('loginRes.authResult --- ', loginRes)
        const { code = '' } = loginRes || {}
        const res = await wxlogin({ code })
        const { errcode = '', errmsg = '', result } = res || {}
        if (!errcode) {
          const { token = '' } = result || {}
          store.setToken(token)
          resolve(res)
        } else {
          reject(errmsg)
        }
      }
    })
  })
  return promise
}

export default requestProxy
